package com.project.base.baseproject.AppCustoms.MyApplication;

import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.support.multidex.MultiDexApplication;

import com.project.base.baseproject.AppCustoms.Tool.CrashHandler;
import com.project.base.baseproject.ModelManager.FileManager.FileManager;
import com.project.base.baseproject.ModelManager.IdentityManager.IdentityManager;
import com.project.base.baseproject.ModelManager.UserMananger.UserManager;
import com.project.base.baseproject.Utikles.ThirdParty.KeepLiveService.KeepLiveService;
import com.squareup.leakcanary.LeakCanary;
import com.zxy.tiny.Tiny;

import java.util.List;

/**
 * Created by mac on 2017/7/11.
 */
//全局应用对象单例
public class MyApplication extends MultiDexApplication {
    //用户模型管理器
    public static UserManager userManager = null;
    //登陆模型管理器
    public static IdentityManager identityManager = null;
    //帮帮文件操作管理器
    public static FileManager fileManager = null;
    private static MyApplication instance = null;
    private CrashHandler crashHandler = null;
    private String processName = "";
    public static MyApplication getInstance() {
        return instance;
    }
    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;
        //在这里对数据库进行初始化
        identityManager = IdentityManager.manager();
        identityManager.readAuthorizeData();
        userManager = UserManager.manager();
        userManager.loadUserInfo();
        fileManager = FileManager.manager();
        fileManager.createFinder();
        //图片压缩三方库在这里初始化
        Tiny.getInstance().init(this);
        //设置异常捕获
        crashHandler = new CrashHandler();
        Thread.setDefaultUncaughtExceptionHandler(crashHandler);
        //检查内存泄露
        LeakCanary.install(this);
    }
    @Override
    protected void attachBaseContext(Context context) {
        super.attachBaseContext(context);
        attach();
    }
    private void attach(){
        processName = getProcessName(this, android.os.Process.myPid());
        if (processName != null) {
            boolean defaultProcess = processName.equals(getPackageName());
            if (defaultProcess) {
                startService(new Intent(this, KeepLiveService.class));
            } else if (processName.contains(":live")) {
            }
        }
    }
    public static String getProcessName(Context cxt, int pid) {
        ActivityManager am = (ActivityManager) cxt.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> runningApps = am.getRunningAppProcesses();
        if (runningApps == null) {
            return null;
        }
        for (ActivityManager.RunningAppProcessInfo procInfo : runningApps) {
            if (procInfo.pid == pid) {
                return procInfo.processName;
            }
        }
        return null;
    }
}
